package com.breeze.leetcode.lcs;

import java.util.Map;

/**
 * @url <a href="https://leetcode.cn/problems/YesdPw">LCS 03. 主题空间</a>
 * @author breeze
 * @date 2025/2/16
 */
public class LCS03YesdPw {

    public static void main(String[] args) {
        LCS03YesdPw solution = new LCS03YesdPw();
        int result = solution.largestArea(new String[]{"110","231","221"});
        System.out.println(result);
    }

    public int largestArea(String[] grid) {
        Topic[][] topics = new Topic[grid.length][grid[0].length()];

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length(); j++) {
                int topic = grid[i].charAt(j) - '0';
                boolean nearCorridor = i == 0 || j == 0 || i == grid.length - 1 || j == grid[i].length() - 1;
                topics[i][j] = new Topic(topic, nearCorridor);
            }
        }

        // 直接遍历内层
        int maxArea = 1;
        for (int i = 1; i < topics.length - 1; i++) {
            for (int j = 1; j < topics[i].length - 1; j++) {
                // 左
                Topic current = topics[i][j];
                calculate(current, topics[i][j - 1]);
                calculate(current, topics[i - 1][j]);

                if (!current.isCorridor && !current.nearCorridor) {
                    maxArea = Math.max(maxArea, current.validSpace);
                }
            }
        }

        return maxArea;
    }

    private void calculate(Topic current, Topic neighbor) {
        if (neighbor.isCorridor) {
            current.nearCorridor = true;
            return;
        }

        if (current.topic == neighbor.topic) {
            current.nearCorridor = neighbor.nearCorridor;
            current.validSpace += neighbor.validSpace;
        }
    }

    static class Topic {
        int topic;
        /**
         * 是否靠走廊
         */
        boolean nearCorridor;
        /**
         * 是否为走廊
         */
        boolean isCorridor;
        /**
         * 可用空间
         */
        int validSpace;

        public Topic(int topic, boolean nearCorridor) {
            this.topic = topic;
            this.nearCorridor = nearCorridor;
            this.validSpace = 1;
            this.isCorridor = topic == 0;
        }

    }
}
